#include "../Tools/GLHeaders.hpp"
#include "../Tools/Texture.hpp"
#include "../Tools/Color.hpp"
#include "../Tools/Interpolation.hpp"
#include "Face.hpp"

Face::Face(void){
   InitTexture();
   InitList();
}

Face::~Face(void){
	glDeleteLists(list_id,1);
  glDeleteTextures(1, &text_id);
}

void Face::Draw(void){
	glCallList(list_id);
}

void Face::InitList(void){
	list_id = glGenLists(1); // create one DisplayList
	
  glNewList(list_id, GL_COMPILE);
  GLfloat coef = 2.0f;
	glPushAttrib(GL_COLOR_BUFFER_BIT|GL_CURRENT_BIT|GL_TEXTURE_BIT);	
	glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, text_id);
	glBegin(GL_TRIANGLES);
	glNormal3f( 0.0f, 0.0f, 1.0f); // Front Face
  glColor3f(1.0f, 1.0f, 1.0f); // color mask
	glTexCoord2f(0.0f, 0.0f);glVertex3f(-1.0f,-1.0f, 0.0f);
	glTexCoord2f(coef, 0.0f);glVertex3f( 1.0f,-1.0f, 0.0f);
	glTexCoord2f(coef, coef);glVertex3f( 1.0f, 1.0f, 0.0f);

	glTexCoord2f(coef, coef);glVertex3f( 1.0f, 1.0f, 0.0f);
	glTexCoord2f(0.0f, coef);glVertex3f(-1.0f, 1.0f, 0.0f);
	glTexCoord2f(0.0f, 0.0f);glVertex3f(-1.0f,-1.0f, 0.0f);
	glEnd();
	glPopAttrib();
	glEndList();
}

void Face::InitTexture(void){
  Texture tex(512, 512);
  Texture fg(512, 512, Color::Color(1.0f, 0.0f, 0.0f, 0.2f));
  
  fg = fg.Circle(
        Vector::Vector(256, 256),
        64.0f,
        128.0f,
        Color::Color(0.4f,0.0f,0.0f,1.0f),
        Color::Color(0.0f,0.0f,0.0f,1.0f),
        QUINTIC);

  tex = tex.Fill(
      Color::Color(1.0f,0.8f,0.0f,1.0f), 
      Color::Color(0.8f,0.4f,0.0f,1.0f), 
      Color::Color(0.8f,0.4f,0.0f,1.0f),
      Color::Color(1.0f,0.8f,0.0f,1.0f),
      NEAREST);
  
  tex = tex.Seamless();
  tex = Texture::Add(fg,tex);
  tex = tex.Inverse();

  glGenTextures(1, &text_id);
	glBindTexture(GL_TEXTURE_2D, text_id);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, mizu);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, tex.width, tex.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLubyte *)tex.data);
}
